package com.future.mayi.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.future.baselib.utils.CommonUtils;
import com.future.mayi.R;
import com.future.mayi.activity.SettingPayPasswordActivity;
import com.future.mayi.view.PasswordView;

/**
 * Created by 周大虎 on 2018/3/9.
 */

public class EdtPasswordDialog extends Dialog {

    private PasswordView passwordView;
    private Activity mContext;

    public EdtPasswordDialog(@NonNull Activity context) {
        super(context, R.style.dialog);
        setCancelable(false);
        init(context);
    }

    private void init(Activity context) {
        this.mContext = context;
        View layout = LayoutInflater.from(context).inflate(R.layout.dialog_edt_password, null);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams((int) (CommonUtils.getScreenSize(context)[0] * 0.8f), ViewGroup.LayoutParams.WRAP_CONTENT);
        setContentView(layout, params);

        passwordView = (PasswordView) findViewById(R.id.edt_password);
        setListener(listener);

        findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        findViewById(R.id.tv_forget).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                mContext.startActivity(new Intent(mContext, SettingPayPasswordActivity.class));
            }
        });

    }

    @Override
    public void show() {
        super.show();
        passwordView.postDelayed(new Runnable() {
            @Override
            public void run() {
                passwordView.requestFocus();
                InputMethodManager imm = (InputMethodManager) passwordView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
            }
        }, 200);
    }

    private PasswordView.PasswordListener listener;

    public void setListener(PasswordView.PasswordListener listener) {
        if (listener == null) return;
        this.listener = listener;
        if (passwordView != null) passwordView.setPasswordListener(listener);
    }

    @Override
    public void dismiss() {
        if (passwordView != null && mContext != null && passwordView.getWindowToken() != null)
            ((InputMethodManager) passwordView.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(passwordView.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        super.dismiss();
    }
}
